<template>
    <view class="info br-24 mt-24">
        <view class="align-center space-between pl-30 pr-30 pt-28 mb-8">
            <view class="ft-32 bold t-3">订房信息</view>
            <view class="align-center space-between">
                <view v-if="roomStock === 1" class="mr-20 c-m">(仅剩1间)</view>
                <hj-number-box
                    v-model="roomNum"
                    :max="roomStock"
                    :min="1"
                    unit="间"
                    size="44rpx"
                    @change="handleChange"
                />
            </view>
        </view>
        <view class="pl-30 pr-30 ft-28 t-3">
            <view class="info-list flex">
                <view class="pr-20 height align-center">住客姓名</view>
                <view class="flex-auto">
                    <view class="height align-center">
                        <up-input
                            placeholder="请输入姓名"
                            v-model="form.name"
                            fontSize="28rpx"
                            :clearable="true"
                            :maxlength="60"
                            @focus="validateForm.nameTips = ''"
                        ></up-input>
                    </view>
                    <view v-if="validateForm.nameTips" class="ft-24 error-msg">
                        {{ validateForm.nameTips }}
                    </view>
                </view>
            </view>

            <view class="info-list flex">
                <view class="pr-20 height align-center">联系电话</view>
                <view class="flex-auto">
                    <view class="height align-center">
                        <up-input
                            placeholder="请输入手机号码"
                            v-model="form.phone"
                            fontSize="28rpx"
                            :clearable="true"
                            :maxlength="11"
                            type="number"
                            @focus="validateForm.phoneTips = ''"
                        ></up-input>
                    </view>
                    <view v-if="validateForm.phoneTips" class="ft-24 error-msg">
                        {{ validateForm.phoneTips }}
                    </view>
                </view>
            </view>
            <view class="info-list align-center">
                <view class="pr-20 height align-center">预计到店</view>
                <view class="flex-auto">
                    <picker @change="changTime" :value="index" :range="array">
                        <view class="ft-28 t-3 space-between">
                            <view>{{ array[timeIndex] }} 房间整晚保留</view>
                            <hj-image
                                src="right-01.png"
                                height="28rpx"
                                width="28rpx"
                                mode="aspectFit"
                            />
                        </view>
                    </picker>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
/**
 * @description
 * @author yinzhi
 * @date 2025-05
 */
import { ref, computed, defineComponent, watch } from 'vue'
import dayjs from 'dayjs/esm/index'
defineComponent({
    name: 'UserInfo'
})
// 接收父组件传值
const props = defineProps({
    info: {
        type: Object,
        default: () => {}
    },
    form: {
        type: Object,
        default: () => {}
    },
    validateForm: {
        type: Object,
        default: () => {}
    }
})

const emit = defineEmits(['update:form', 'update:validateForm', 'change'])

import { useStore } from 'vuex'
const store = useStore()
// 入住信息
const checkInInfo = computed(() => store.state.platform.checkInInfo || '')
// 最早入住时间
const earliestTime = computed(() => props.info.hotelPolicy?.checkInTime || '14:00:00')

const roomNum = ref(1)

// 房源库存
const roomStock = computed(() => {
    return props.info.roomTypeInfoDetailResp?.stockNum || null
})

// 入住时间选择
const array = ref([])
const timeIndex = ref(0)
// 入住时间实际时间
const arrivalTime = ref([])

// 更新 arrivalTime 并触发事件
const updateArrivalTime = () => {
    const newForm = { ...props.form, arrivalTime: arrivalTime.value[timeIndex.value] }
    emit('update:form', newForm)
}

// 选择到店时间
const changTime = e => {
    timeIndex.value = e.detail.value
    updateArrivalTime()
}

const handleChange = e => {
    roomNum.value = e.value
    emit('change', e)
}

watch(
    [() => checkInInfo.value.roomAmount, () => roomStock.value],
    ([newRoomAmount, newStock]) => {
        if (newStock === null) return
        if (newStock < newRoomAmount) {
            roomNum.value = newStock
        } else {
            roomNum.value = newRoomAmount
        }
        emit('change', { value: roomNum.value })
    },
    { immediate: true }
)

// 监听earliestTime变化，并根据earliestTime的值拿出距离第二天六点所有的整点时间节点
watch(
    earliestTime,
    () => {
        if (!earliestTime.value) return
        const time = dayjs(
            checkInInfo.value.startDate + ' ' + earliestTime.value,
            'YYYY-MM-DD HH:mm:ss'
        )
        const arr = []
        const arrivalTimes = []
        // 获取当前时间的小时数（向上取整）
        const currentHour = Math.ceil(time.hour())
        // 从当前小时+1开始，到23点
        for (let i = currentHour; i <= 23; i++) {
            // 跳过比当前时间早的时间点
            if (i <= currentHour && time.minute() > 0) continue
            const hour = i < 10 ? `0${i}` : i
            arr.push(`${hour}:00`)
            arrivalTimes.push(
                dayjs(checkInInfo.value.startDate)
                    .hour(i)
                    .minute(0)
                    .second(0)
                    .format('YYYY-MM-DD HH:mm:ss')
            )
        }
        // 2. 处理次日时间（0点到6点）
        for (let i = 0; i <= 6; i++) {
            arr.push(`次日${i}点`)
            arrivalTimes.push(
                dayjs(checkInInfo.value.startDate)
                    .add(1, 'day')
                    .hour(i)
                    .minute(0)
                    .second(0)
                    .format('YYYY-MM-DD HH:mm:ss')
            )
        }
        // 更新array的值
        array.value = arr
        arrivalTime.value = arrivalTimes
        updateArrivalTime()
    },
    { immediate: true }
)
</script>

<style scoped lang="scss">
.info {
    background: $uni-bg-color;
    box-shadow: 0 0 10rpx 0 rgba($color: #000000, $alpha: 0.08);
    &-list {
        border-bottom: 1px solid $uni-bg-color-hover;
        .height {
            height: 96rpx;
        }
    }
    &-list:last-child {
        border: none;
    }
    .error-msg {
        border-bottom: 1px solid $uni-color-error;
        color: $uni-color-error;
        margin-top: -10rpx;
    }
}
</style>
